<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        shape="round"
        show-action
        v-model="searchText"
        placeholder="请输入搜索关键词"
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <searchResult v-if="isResultShow" :search-text="searchText"></searchResult>
    <!-- 联想建议 -->
    <searchSuggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></searchSuggestion>
    <!-- 历史记录 -->
    <searchHistory v-else :search-history="searchHistory" @search="onSearch"></searchHistory>
  </div>
</template>

<script>
import searchSuggestion from '@/views/search/components/search-suggestion'
import searchHistory from '@/views/search/components/search-history'
import searchResult from '@/views/search/components/search-result'
import { getSearchhistory } from '@/api/search'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      // 搜索文本
      searchText: '',
      isResultShow: false,
      searchHistory: []
    }
  },
  computed: {
    ...mapState(['user'])
  },
  components: { searchSuggestion, searchHistory, searchResult },
  async created () {
    this.loadSearchHistories()
  },
  methods: {
    onSearch (searchText) {
      this.searchText = searchText
      // 将历史记录push保存
      const index = this.searchHistory.indexOf(searchText)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(searchText)
      window.localStorage.setItem(
        'search-history',
        JSON.stringify(this.searchHistory)
      )
      this.isResultShow = true
    },
    async loadSearchHistories () {
      let searchHistories =
        JSON.parse(window.localStorage.getItem('search-history')) || []
      if (this.user) {
        const { data } = await getSearchhistory()
        searchHistories = [...new Set([...searchHistories, ...data.data.keywords])]
      }
      this.searchHistory = searchHistories
    }
  }
}
</script>

<style>
</style>
